package com.example.goods.controller;

import com.example.goods.bean.User;
import com.example.goods.common.Const;
import com.example.goods.common.ResultResponse;
import com.example.goods.service.UserService;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

/**
 * Created by IntelliJ IDEA.
 *用户模块
 * @author ouyangzhixiang
 * @date 2018/7/4
 */
@CrossOrigin
@RequestMapping("/user/")
@RestController
@AllArgsConstructor
public class UserController {
    private final UserService userService;

    /**
     * 用户登录
     * @param username
     * @param password
     * @param httpSession
     * @return
     */
    @PostMapping("login")
    public ResultResponse<User> login(String username, String password, HttpSession httpSession){
        ResultResponse<User> response =userService.login(username,password);
        if (response.isSuccess()){
            httpSession.setAttribute(Const.CURRENT_USER,response.getData());
        }
        return response;
    }

    /**
     * 用户退出
     * @param httpSession
     * @return
     */
    @GetMapping("login_out")
    public ResultResponse loginOut(HttpSession httpSession){
        httpSession.removeAttribute(Const.CURRENT_USER);
        return ResultResponse.createBySuccessMessage("退出登录");
    }

    /**
     * 获取用户登录信息
     */
    @GetMapping("login_info")
    public ResultResponse<User> loginInfo(HttpSession httpSession){
      User user= (User) httpSession.getAttribute(Const.CURRENT_USER);
      if (user!=null){
          return ResultResponse.createBySuccess(user);
      }
      return ResultResponse.createByErrorMessage("用户未登录");
    }
}
